<template>
  <div>
    <el-tree
      ref="tree"
      :data="list"
      show-checkbox
      node-key="id"
      :props="{ children: 'children',label: 'name'}"
      :default-expand-all="true"
      :check-strictly="true"
    />
    <el-row type="flex" justify="end">
      <el-button size="small" type="success" @click="Hsubmit">
        分配权限
      </el-button> <el-button size="small" type="info" @click="$emit('close')">
        取消
      </el-button>
    </el-row>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permisson'
import { tranDataToTree } from '@/utils/index.js'
import { getRoleDetail, assignPerm } from '@/api/settings.js'
export default {
  props: {
    // 接收父组件传递过来当前被点击的id
    rowId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [] // 保存获取到的权限点
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    // 点击了 确定 分配权限
    async Hsubmit() {
      try {
        const permIds = this.$refs.tree.getCheckedKeys()
        const res = await assignPerm({ id: this.rowId, permIds: permIds })
        // console.log('assignPerm', res)
        // 保存数据
        if (res.code !== 10000) return
        this.$message.success(res.message)
        this.$emit('close')
      } catch (err) {
        console.log('assignPerm', err)
      }
    },
    // 获取权限列表
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        // console.log('getPermissionList', res)
        // 保存数据
        if (res.code !== 10000) return
        this.list = tranDataToTree(res.data)
        // 获取当前角色的详情 已经拥有的权限
        const info = await getRoleDetail(this.rowId)
        // console.log('getRoleDetail', info)
        // info.data.permIds 当前角色拥有的权限
        this.$refs.tree.setCheckedKeys(info.data.permIds)
      } catch (err) {
        console.log('getPermissionList', err)
      }
    }
  }
}
</script>
